<template>
    <div class="default-main">
        <el-dialog v-model="outerVisible" :close-on-click-modal="false" title="编辑" width="60%">
            <el-form :model="form" label-width="auto" style="max-width: 90%">
                <el-form-item label="用户名">
                    <el-input v-model="form.username" />
                </el-form-item>
                <el-form-item label="用户姓名">
                    <el-input v-model="form.username_show" />
                </el-form-item>
                <el-form-item label="密码">
                    <el-input type="password" show-password v-model="form.password" />
                </el-form-item>
                <el-form-item label="电子邮件">
                    <el-input v-model="form.email" />
                </el-form-item>
                <el-form-item label="角色">
                    <el-select
                        v-model="form.roles"
                        multiple
                        >
                        <el-option
                            v-for="item in role_data"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input type="textarea" :rows="3" v-model="form.remark" />
                </el-form-item>
                <el-form-item label="用户状态">
                    <el-switch v-model="form.status" />
                </el-form-item>
                <!-- <el-form-item label="权限"> -->
                    <el-scrollbar height="150px" width="100%">
                        <el-tree
                            ref="treeRef"
                            style="max-width: 600px"
                            :data="data"
                            show-checkbox
                            default-expand-all
                            node-key="id"
                            highlight-current
                            :props="defaultProps"
                            :default-checked-keys="checkedKeys"
                        />
                    </el-scrollbar>
                <!-- </el-form-item> -->
            </el-form>
            
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="outerVisible = false">取消</el-button>
                    <el-button type="primary" @click="saveuser">
                    保存
                    </el-button>
                </div>
            </template>
        </el-dialog>
        <vxe-grid ref="gridRef" v-bind="gridOptions" v-on="gridEvents"></vxe-grid>
    </div>
</template>
<script setup>
import { onMounted, ref, reactive } from 'vue'
import { ElLoading,ElButton, ElDialog, ElForm } from 'element-plus';
import {callBackApi} from '../../../api'
import { ElTree,ElMessageBox } from 'element-plus'
const loading = ref(false);
const openLoading = () => {
    loading.value = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)'
    })
}
const closeLoading = () => {
    loading.value.close()
}
const role_data = ref([])
const outerVisible = ref(false)
const gridRef = ref({})
const data = ref([])
const treeRef = ref([])
const checkedKeys = ref([])
const defaultProps = {
  children: 'children',
  label: 'title',
}
const form = reactive({
    id: '',
    username: '',
    username_show: '',
    password: '',
    email: '',
    remark: '',
    roles: [],
    status: true
})

//清理表单数据
const clearForm = () => {
    form.id = ''
    form.username = ''
    form.username_show = ''
    form.password = ''
    form.email = ''
    form.remark = ''
    form.roles = []
    form.status = true
    checkedKeys.value = []
}
//初始化table数据
const initTableData = async () => {
    gridOptions.loading = true
    let params = {
        page: gridOptions.pagerConfig.currentPage,
        size: gridOptions.pagerConfig.pageSize,
        query:{
            username__contains: gridOptions.formConfig.data.username__contains,
            //app__name__contains: gridOptions.formConfig.data.app__name__contains
        }
    }
    let res = await callBackApi(
        "base/userList/",
        params,
        {loading:false},
        {}
    )
    if (res.code === 200) {
        gridOptions.data = res.data
        gridOptions.pagerConfig.total = res.total
    }
    gridOptions.loading = false
}

//初始化角色数据
const initRoleData = async () => {
    let res = await callBackApi(
        "base/roleSelectList/",
        null,
        {loading:false},
        {}
    )
    if (res.code === 200) {
        role_data.value = res.data
    }
}

const initreedata = async () => {
    let res = await callBackApi(
        "base/getPermissionTree/",
        null,
        {loading:true},
        {lock: true,text: 'Loading',background: 'rgba(0, 0, 0, 0.7)'}
    );
    if (res.code === 200) {
        data.value = res.data
    }
}
onMounted( async () => {
    await initTableData()
})
const gridOptions = reactive({
    border: true,
    stripe: true,
    size: 'small',
    height:'auto',
    customConfig: {
        placement: 'bottom-right',
        mode:'modal'
    },
    loading: false,
    toolbarConfig: {
        custom: true,
        buttons: [
            { name: '新增', code: 'add', status: 'primary' },
            { name: '删除', code: 'del', status: 'error' }
        ]
    },
    formConfig: {
        data: {
            username__contains: '',
            app__name__contains: ''
        },
        items: [
            { field: 'name', title: '用户名', itemRender: { name: 'VxeInput' } },
            { field: 'username_show', title: '用户姓名', itemRender: { name: 'VxeInput' } },
            { field: 'app_id', title: '所属应用ID', itemRender: { name: 'VxeInput' } },
            {
                itemRender: {
                name: 'VxeButtonGroup',
                options: [
                    { type: 'submit', content: '搜索', status: 'primary' },
                ]
                }
            }
        ]
    },
    pagerConfig: {
        total: 0,
        currentPage: 1,
        pageSize: 20,
        layouts: ['Home', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'End', 'Sizes', 'FullJump', 'Total']
    },
    checkboxConfig: {
        highlight: true
    },
    columns: [
        { type: 'checkbox', width: 40 },
        { type: 'seq', width: 70 },
        { field: 'username', title: '用户名' },
        { field: 'username_show', title: '用户姓名' },
        { field: 'email', title: '电子邮箱' },
        { field: 'status', title: '状态' },
    ],
    data:[]
});
const gridEvents = {
    async formSubmit () {
        await initTableData()
    },
    async toolbarButtonClick (params) {
        switch (params.code) {
            case 'add':
                clearForm()
                initRoleData()
                initreedata()
                outerVisible.value = true
                break;
            case 'del':
                const $grid = gridRef.value
                if(!$grid){
                    ElMessageBox.alert('无数据', '提示',{})
                    return
                }
                let ids = $grid.getCheckboxRecords().map(item => item.id)
                if (ids.length === 0) {
                    ElMessageBox.alert('请选择要删除的记录', '提示', {
                        confirmButtonText: '确定'
                    })
                    return
                }
                let confirm = await ElMessageBox.confirm('确认删除所选记录吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                if (confirm) {
                    let res = await callBackApi(
                        "base/deleteUser/",
                        {ids: ids},
                        {loading:true},
                        {lock: true,text: 'Loading',background: 'rgba(0, 0, 0, 0.7)'}
                    )
                    if (res.code === 200) {
                        await initTableData()
                    } else {
                        ElMessageBox.alert(res.msg, '提示', {
                            confirmButtonText: '确定'
                        })
                    }
                }
                break;
            default:
                break;
        }
    },
    async cellDblclick ({ row }) {
        clearForm()
        await initRoleData()
        await initreedata()
        let res = await callBackApi(
            "base/userDetail/",
            {id: row.id},
            {loading:true},
            {lock: true,text: 'Loading',background: 'rgba(0, 0, 0, 0.7)'}
        )

        if (res.code === 200) {
            row = res.data
            form.id = row.id
            form.username = row.username
            form.username_show = row.username_show
            form.email = row.email
            form.remark = row.remark
            form.roles = row.role_ids
            form.status = row.status
            checkedKeys.value = row.permission_ids
        }
        
        outerVisible.value = true
    },
}
const saveuser = async () => {
    let params = {
        id: form.id,
        username: form.username,
        username_show: form.username_show,
        password: form.password,
        email: form.email,
        remark: form.remark,
        roles: form.roles,
        status: form.status,
        permissions: treeRef.value.getCheckedKeys()
    }
    let res = await callBackApi(
        "base/saveUser/",
        params,
        {loading:true},
        {lock: true,text: 'Loading',background: 'rgba(0, 0, 0, 0.7)'}
    )
    
    if (res.code === 200) {
        clearForm()
        await initTableData()
        outerVisible.value = false
    } else {
        ElMessageBox.alert(res.msg, '提示', {
            confirmButtonText: '确定'
        })
    }
}
</script>
<style scoped lang="scss">
.default-main {
    height: 96%;
}
</style>